﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VoiceAd.DAL;
using VoiceAd.Models;
using System.IO;
using System.Text;
using System.Web.Security;

namespace VoiceAd.Controllers
{
    public class StationController : Controller
    {
        private IlogRepository logRepository = new LogRepository(new dbVoiceAdDataContext());
        private IStationRepository stationRepository = new StationRepository(new dbVoiceAdDataContext());
        private IDistrictRepository districtRepository = new DistrictRepository(new dbVoiceAdDataContext());
        private IProvinceRepository provinceRepository = new ProvinceRepository(new dbVoiceAdDataContext());
        private ICampaignRepository campaignRepository = new CampaignRepository(new dbVoiceAdDataContext());
        private IMonitorRepository monitorRepository = new MonitorRepository(new dbVoiceAdDataContext());
        private ICompanyRepository companyRepository = new CompanyRepository(new dbVoiceAdDataContext());
        private IBlockRepository blockRepository = new BlockRepository(new dbVoiceAdDataContext());
        private IBookingRepository bookingRepository = new BookingRepository(new dbVoiceAdDataContext());
        private IServicesRepository servicesRepository = new ServicesRepository(new dbVoiceAdDataContext());

        [Authorize(Roles = "Station")]
        public ActionResult Index()
        {
            ViewBag.lstActive = campaignRepository.GetListActiveCampaignsbyStationId();
            ViewBag.lstCampaign = campaignRepository.GetListCampaignsbyStationId();
            if (stationRepository.GetStationByUser() != null)
            {
                ViewBag.StationId = stationRepository.GetStationByUser().Id;
            }
            subMenuServices();
            return View();
        }

        public void subMenuServices()
        {
            StringBuilder str = new StringBuilder();
            str = str.AppendLine("<ul class='sub-options'>");
            IEnumerable<tblServices> lstServices = servicesRepository.GetListService();
            foreach (tblServices tbl in lstServices)
            {
                string lUrl = Url.Content("~/service-" + VoiceAd.Common.UrlEncode.ToFriendlyUrl(tbl.Title_Vn) + "-" + tbl.Id.ToString() + ".html");
                str.AppendLine("<li><a href=" + lUrl + ">" + tbl.Title_Vn + "</a></li>");
            }
            str = str.AppendLine("</ul>");
            ViewBag.lstSubMenu = str.ToString();
        }

        [Authorize(Roles = "Station")]
        public ActionResult Campaign(int id)
        {
            tblCampaign tbl = campaignRepository.GetCampaignById(id);
            ViewBag.lstMonitor = monitorRepository.GetListMonitorsByStationId(id);
            subMenuServices();
            return View(tbl);
        }

        [Authorize(Roles = "Station")]
        [HttpPost]
        public ActionResult Campaign(string txtDay, string txtUrl, string CampId)
        {
            tblMonitor tbl = new tblMonitor();
            tblStation objStation = stationRepository.GetStationByUser();
            tblBooking objBook = bookingRepository.GetBookingByCampId(int.Parse(CampId), objStation.Id);
            tblCampaign objCamp = campaignRepository.GetCampaignById(int.Parse(CampId));

            tbl.BookingId = objBook.Id;

            tbl.UploadDay = DateTime.Parse(string.Format("{0:yyyy/MM/dd}", txtDay));

            if (!string.IsNullOrEmpty(txtUrl) && txtUrl.Contains(";"))
                txtUrl = txtUrl.Replace(";", "");

            int intCount = monitorRepository.GetSumMonitorByUploadDay(objBook.Id, tbl.UploadDay.Value);

            tbl.UrlFile = UpdateFile(txtUrl, objCamp.Title, tbl.UploadDay.Value.ToString("yyyyMM"), tbl.UploadDay.Value.ToString("yyyyMMdd"), intCount, objStation.UserName);
            monitorRepository.InsMonitor(tbl);

            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = objStation.StationName + " Upload file monitor ngày: " + DateTime.Parse(string.Format("{0:yyyy/MM/dd}", txtDay));
            tbllog.Description = "Chiến dịch " + objCamp.Title;
            logRepository.InsLog(tbllog);

            return RedirectToAction("Campaign", new { id = CampId });
        }

        protected override void Dispose(bool disposing)
        {
            campaignRepository.Dispose();
            stationRepository.Dispose();
            monitorRepository.Dispose();
            bookingRepository.Dispose();
            districtRepository.Dispose();
            provinceRepository.Dispose();
            companyRepository.Dispose();
            blockRepository.Dispose();
            servicesRepository.Dispose();
        }

        public string UpdateFile(string strName, string strCamp, string strDate, string strDay, int intCount, string StationName)
        {
            string strPath = Server.MapPath("~/uploads");
            string strFile = Path.Combine(Server.MapPath("~/uploads"), strName);
            string strExt = Path.GetExtension(strFile);
            string strFolder = Path.Combine(strPath, "Station");
            string strIdCamp = string.Empty;
            string strIdDate = string.Empty;

            if (!Directory.Exists(strFolder))
                Directory.CreateDirectory(strFolder);

            strIdCamp = Path.Combine(strFolder, strCamp);

            if (!Directory.Exists(strIdCamp))
                Directory.CreateDirectory(strIdCamp);

            strIdDate = Path.Combine(strIdCamp, strDate);

            if (!Directory.Exists(strIdDate))
                Directory.CreateDirectory(strIdDate);

            string strResult = StationName + "-" + strDay + "-0" + (intCount + 1).ToString() + strExt;

            strFolder = Path.Combine(strIdDate, strResult);

            System.IO.File.Move(strFile, strFolder);

            //System.IO.File.Delete(strFile);

            return "Station/" + strCamp + "/" + strDate + "/" + strResult;
        }

        [Authorize(Roles = "Station")]
        public ActionResult ViewSchedule(int CamId, int StationId, int monthId)
        {
            ViewBag.lstData = campaignRepository.PrintSchedule(CamId, StationId, monthId);
            ViewBag.CountDay = campaignRepository.GetCountDay(CamId, StationId, monthId);
            tblStation tblst = stationRepository.GetStationById(StationId);
            ViewBag.lStationVsProvince = "Đài truyền thanh " + tblst.StationName + " _ " + tblst.tblDistrict.tblProvince.ProvinceName;

            tblCompany tblcp = companyRepository.GetListCompanys().First();
            ViewBag.CompantName = tblcp.CompanyName_Vn;
            ViewBag.DiaChi = tblcp.Address_Vn;
            ViewBag.PhoneFax = "Tel " + tblcp.Telephone + ", Fax" + tblcp.Fax;
            ViewBag.MST = "Mã số thuế: " + tblcp.TaxCode;
            ViewBag.CampaignId = CamId;
            ViewBag.lCampaignName = campaignRepository.GetCampaignById(CamId).Title;

            tblBooking tblbk = bookingRepository.GetBookingByCampId(CamId, StationId);
            IEnumerable<tblBlock> lsttblbl = blockRepository.GetByBookingID(tblbk.Id);

            string lMounth = "Tháng ";
            foreach (tblBlock tbl in lsttblbl)
            {
                if (monthId == tbl.MonthBook)
                {
                    lMounth = lMounth + tbl.MonthBook + "/" + tbl.YearBook;
                }
            }

            ViewBag.ThoiGianPhat = lMounth;

            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = tblst.StationName + " In lịch phát sóng tháng: " + lMounth;
            tblCampaign tblCam = campaignRepository.GetCampaignById(CamId);
            tbllog.Description = "Chiến dịch " + tblCam.Title;
            logRepository.InsLog(tbllog);

            return View();
        }

        [Authorize(Roles = "Station")]
        public ActionResult ListCertificate(int CamId, int StationId, int MonthBook, int YearBook)
        {
            tblStation tblst = stationRepository.GetStationById(StationId);
            ViewBag.lStation = "Đài truyền thanh " + tblst.StationName;
            ViewBag.lProvince = tblst.tblDistrict.tblProvince.ProvinceName;
            ViewBag.lInfomation = "Đài truyền thanh " + tblst.StationName + " _ " + tblst.tblDistrict.tblProvince.ProvinceName + " xác nhận đã phát sóng mẫu quảng cáo ' " + campaignRepository.GetCampaignById(CamId).Title + " '";
            ViewBag.CountDay = campaignRepository.GetCountDay(CamId, StationId, MonthBook);

            ViewBag.lstData = campaignRepository.PrintCertificates(CamId, StationId, MonthBook);
            ViewBag.MonthId = MonthBook;
            ViewBag.YearId = YearBook;
            ViewBag.CampaignId = CamId;

            tblLog tbllog = new tblLog();
            tbllog.UserName = Membership.GetUser().UserName;
            tbllog.CreateDate = DateTime.Now;
            tbllog.ActionName = tblst.StationName + " In chứng nhận phát sóng tháng: " + MonthBook + "/" + YearBook;
            tblCampaign tbl = campaignRepository.GetCampaignById(CamId);
            tbllog.Description = "Chiến dịch " + tbl.Title;
            logRepository.InsLog(tbllog);

            return View();
        }
    }
}
